package cn.songdragon.zboschina.crawler;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.songdragon.zboschina.HttpClient;
import cn.songdragon.zboschina.proxy.ProxySingleton;

public class ProxyFlightCrawlerExecutorService {

	private static final Logger logger = LoggerFactory.getLogger(ProxyFlightCrawlerExecutorService.class);

	ExecutorService executorService = Executors.newFixedThreadPool(10);
	AtomicInteger count = new AtomicInteger(0);
	AtomicInteger responseCount = new AtomicInteger(0);

	public ProxyFlightCrawlerExecutorService() throws IOException {
		startLoadThread();
	}

	public void getUrl(String url) {

		executorService.submit(new Runnable() {

			@Override
			public void run() {
				ProxyFlightCrawler pfc = new ProxyFlightCrawler();
				pfc.setHttpClient(HttpClient.getInstance());
				pfc.setProxyManager(ProxySingleton.getProxyManagerInstance());

				String refererUrl = "http://flights.ctrip.com/booking/SHA-XNN-day-1.html?DDate1=2016-04-05";
				Map<String, String> header = new HashMap<>();
				header.put(HttpHeaders.REFERER, refererUrl);
				header.put(HttpHeaders.HOST, "flights.ctrip.com");
				header.put(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				header.put(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
				header.put(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
				header.put("cookie",
						"_abtest_userid=c9ab07ec-9091-4d3b-9002-b17120b1d62f; "
								+ "traceExt=campaign=CHNbaidu81&adid=index; "
								+ "ASP.NET_SessionSvc=MTAuMTUuMTM2LjI1fDkwOTB8b3V5YW5nfGRlZmF1bHR8MTQ0OTA1MTEzNzk2NQ; "
								+ "ticket_ctrip=uoeOwviAJ6VQEgTNwLuTqSV9j/bS+aOP3Riia1P+kyQbgkQZsD2giY6h2Z/ssJopnUuKOPLkYWPreQ9"
								+ "/jtY2Svo2r9h8PcVvmH7X7UIL7TXfaMTsDvhLT6erFPDPSe9jhSBTGdWYQXCw283nA8A6psAlBrf9vJpHp/"
								+ "QGwzV94lq40u+EvZL3VwyhDBPI+6lbhOfFDbBEGEzsVqM9Y8aWEXqsNeT2BPRqTSJPxbW7+M91B3gWJVwpVi"
								+ "QXX+YqCcqH+48cpgp5mo3NnYGIdrKT2w==; corpid=; corpname=; "
								+ "CtripUserInfo=VipGrade=0&UserName=%cb%ce%d5%d8%cc%da"
								+ "&NoReadMessageCount=0&U=4C2487BA71ABED5E9068838DC9901CE9; "
								+ "AHeadUserInfo=VipGrade=0&UserName=%cb%ce%d5%d8%cc%da&NoReadMessageCount=0&"
								+ "U=4C2487BA71ABED5E9068838DC9901CE9; SMBID=; LoginStatus=1%7cmxg53lamj3wsw5ajx553xg1o480501%2c; "
								+ "login_uid=76D82BDA069092B3FD47B1DC3B45D9B2; login_type=0; "
								+ "login_cardType=0; TraceSession=1942475417; __utma=1.1583353165.1445006533.1459074273.1459074273.1; "
								+ "__utmc=1; __utmz=1.1459074273.1.1.utmcsr=open.ctrip.com|utmccn=(referral)"
								+ "|utmcmd=referral|utmcct=/help/License.aspx; __gads=ID=9a2fdb8f3c59050a:"
								+ "T=1459074650:S=ALNI_MY6VoCw_Dnwl4G3InT66BD9f-LSbA; ibulanguage=EN; "
								+ "history=%5B%7B%22type%22%3A%22OW%22%2C%22searchdate%22%3A%222016-03-27T16%3A18%3A26"
								+ ".970Z%22%2C%22hlist%22%3A%5B%7B%22DcityCode%22%3A%22SHA%22%2C%22AcityCode%2"
								+ "2%3A%22BJS%22%2C%22Ddate%22%3A%222016-03-31%22%2C%22Adate%22%3A%22%22%2C%22currency"
								+ "str%22%3A%22CNY%22%2C%22LowestPrice%22%3A%22640%22%7D%5D%2C%22dCity%22%3A%7B%22display"
								+ "%22%3A%22Shanghai%22%2C%22data%22%3A%22%7CShanghai%7CSHA%22%7D%2C%22aCity%22%3A%7B%2"
								+ "2display%22%3A%22Beijing%22%2C%22data%22%3A%22%7CBeijing%7CBJS%22%7D%7D%5D; "
								+ "TracingErrorFlag=d1b1402a501bdcb; Union=SID=155950&AllianceID=4897&OUID=000401app-;"
								+ " Session=SmartLinkCode=U155950&SmartLinkKeyWord=&SmartLinkQuary=&"
								+ "SmartLinkHost=&SmartLinkLanguage=zh; appFloatCnt=2; FD_SearchHistorty={\"type\":\"S\",\"data\""
								+ ":\"S%24%u4E0A%u6D77%28SHA%29%24SHA%242016-04-05%24%u897F%u5B81%28XNN%29%24XNN%24%24%24\"}; "
								+ "_bfa=1.1445006529677.36dtit.1.1459095508794.1459101333276.4.32; __zpspc=9.3.1459101336.1459101350.3%231%7C%7C%7C%7C%25E6%2590%25BA%25E7%25A8%258B%25E6%2597%2585%25E8%25A1%258C%25E7%25BD%2591%2520%25E6%259C%25BA%25E7%25A5%25A8%25E6%259F%25A5%25E8%25AF%25A2%2520json%7C%23; _ga=GA1.2.1583353165.1445006533; _jzqco=%7C%7C%7C%7C1459073015326%7C1.1298091045.1445006532672.1459101347187.1459101350756.1459101347187.1459101350756.undefined.0.0.9.9;"
								+ " _bfi=p1%3D101027%26p2%3D101027%26v1%3D32%26v2%3D31");
				String body = pfc.queryFlight(url, header);
				// for test
				if (!body.isEmpty() && body.startsWith("{") && body.contains("MU")) {
					logger.error("Get correct response:" + body);
					count.getAndIncrement();
				}
				if (!body.isEmpty() && body.startsWith("{") && body.contains("lps")) {
					responseCount.getAndIncrement();
				}
			}
		});
	}

	public long getCompletedTaskCount() {
		ThreadPoolExecutor tpe = (ThreadPoolExecutor) this.executorService;
		return tpe.getCompletedTaskCount();
	}

	public int getSuccessResponseCount() {
		return this.count.get();
	}

	public int getResponseCount() {
		return this.responseCount.get();
	}

	public void shutdown() {
		this.executorService.shutdown();
	}

	private void startLoadThread() {
		Thread t = new Thread() {
			public void run() {
				InputStream proxyFile = this.getClass().getResourceAsStream("/proxy.txt");
				try {
					ProxySingleton.getProxyManagerInstance().loadProxyFromFileStream(proxyFile);
				} catch (IOException e) {
					// e.printStackTrace();
				}
				logger.error("Avaliable count of proxies="
						+ ProxySingleton.getProxyManagerInstance().getAvaliableProxyCount());
			}
		};
		t.start();
	}
}
